package com.example.gameapplication.bullet;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.DisplayMetrics;

import com.example.gameapplication.BaseObject;
import com.example.gameapplication.R;
import com.example.gameapplication.database.DataUtils;

import java.util.Random;

public class BulletBuff extends BaseObject {


    private Bitmap bullet_buff;
    int moveType;//飞行方向。1左，2右
    long moveTime;//飞行指定方向的次数
    private int heightPixels;
    private int widthPixels;

    public BulletBuff(Resources resources, Paint paint) {
        super(resources, paint);
        setAlive(false);//buff20秒之后才出现
    }

    @Override
    public void initBitmap() {
        bullet_buff = BitmapFactory.decodeResource(resources, R.drawable.bullet_buff);
        object_width = bullet_buff.getWidth();
        object_height = bullet_buff.getHeight();
        DisplayMetrics dm = resources.getDisplayMetrics();
        widthPixels = dm.widthPixels;
        heightPixels = dm.heightPixels;
    }


    @Override
    public void drawSelf(Canvas canvas) {
        if (!isAlive() || getCd() > 0) return;
        canvas.save();
        drawBuff(canvas);
        canvas.restore();
    }

    private void drawBuff(Canvas canvas) {
        canvas.clipRect(leftx, lefty, rightx, righty);
        canvas.drawBitmap(bullet_buff, leftx, lefty, paint);
        logic();
    }

    //飞行逻辑
    public void logic() {

        if (speed == 0) {//移动速度speed
            speed = 20;
        }
//            midx = random.nextInt() % 2 == 0 ? midx - speed : midx + speed;
        if (moveTime <= 0 || moveType == 0)
            if (random.nextBoolean()) {
                moveType = 1;
                moveTime = random.nextInt(14);
            } else {
                moveType = 2;
                moveTime = random.nextInt(14);
            }

        switch (moveType) {
            case 1:
                midx = midx - speed <= 0 ? 0 : midx - speed;
                break;
            case 2:
                midx = midx + speed >= widthPixels ? widthPixels : midx + speed;
                break;
        }
        moveTime--;
        midy = midy + speed;
        setSeat(this.midx, this.midy);
        if (midy > heightPixels) midy = 0;
    }

    @Override
    public void dataDestroyed() {
        if (!bullet_buff.isRecycled()) {
            bullet_buff.recycle();
        }
    }

}
